// stores/taskStore.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useTaskStore = defineStore('tasks', () => {
  const tasks = ref([])
  const members = ref([
    { id: 1, name: '李华', capacity: 8, currentLoad: 0 },
    { id: 2, name: '王芳', capacity: 6, currentLoad: 0 }
  ])
  
  // 计算属性：按状态分类的任务
  const tasksByStatus = computed(() => {
    return {
      todo: tasks.value.filter(t => t.status === 'todo'),
      doing: tasks.value.filter(t => t.status === 'doing'),
      done: tasks.value.filter(t => t.status === 'done')
    }
  })
  
  // 添加新任务
  const addTask = (task) => {
    tasks.value.push({
      id: Date.now(),
      ...task,
      status: 'todo',
      createdAt: new Date()
    })
  }
  
  // 更新任务状态
  const updateTaskStatus = (taskId, newStatus) => {
    const task = tasks.value.find(t => t.id === taskId)
    if (task) task.status = newStatus
  }
  
  // 智能分配任务
  const autoAssignTask = (taskId) => {
    const task = tasks.value.find(t => t.id === taskId)
    if (!task) return
    
    // 找到工作量最少的成员
    const availableMember = [...members.value]
      .sort((a, b) => a.currentLoad - b.currentLoad)[0]
    
    if (availableMember && availableMember.currentLoad < availableMember.capacity) {
      task.assignedTo = availableMember.id
      availableMember.currentLoad += 1
    }
  }
  
  return { tasks, members, tasksByStatus, addTask, updateTaskStatus, autoAssignTask }
})